#include "file_util.h"
#include <string.h>
#include <shlobj.h>
#include <io.h>
#include <stdio.h>

/*
BOOL Wstr2Cstr(char* cstrBuf, DWORD bufSize, const wchar_t* wstr)
{
	size_t converted = 0;
	wcstombs_s(&converted, cstrBuf, bufSize, wstr, _TRUNCATE);
	return(converted != 0);
}

BOOL Cstr2Wstr(wchar_t* wstrBuf, DWORD bufSize, const char* cstr)
{
	size_t converted = 0;
	mbstowcs_s(&converted, wstrBuf, bufSize, cstr, _TRUNCATE);
	return(converted != 0);
}
*/

BOOL IsAbsPath(const char* path)
{
	return(path[0] == '\\' || strstr(path, ":\\") || strstr(path, "\\\\"));
}

BOOL GetDirFromHostPath(char dirBuf[], DWORD bufSize, const char* hostPath)
{
	const char* plast = strrchr(hostPath, '\\');
	if (plast == NULL) {
		return(FALSE);
	}
	DWORD dirLen = DWORD(plast - hostPath);
	strncpy_s(dirBuf, bufSize, hostPath, dirLen);
	dirBuf[dirLen] = '\0';
	return(TRUE);
}

const char* GetFileFromPath(const char* hostPath)
{
	const char* pfirst = strrchr(hostPath, '\\');
	if (pfirst != NULL) {
		pfirst += 1;
	} else {
		pfirst = hostPath + 0;
	}
	return(pfirst);
}

BOOL GetActionDeskDir(char dirBuf[], DWORD bufSize)
{
	if ((SHGetSpecialFolderPathA(NULL, dirBuf, CSIDL_PERSONAL, FALSE))) {
		strcat_s(dirBuf, bufSize, "\\ActionDesk");
		return(TRUE);
	}
	else {
		return(FALSE);
	}
}

BOOL GetActionProductDir(char dirBuf[], DWORD bufSize, const char* configSuffix)
{
	char actionDir[256];
	if (GetActionDeskDir(actionDir, sizeof(actionDir))) {
		strcpy_s(dirBuf, bufSize, actionDir);
		strcat_s(dirBuf, bufSize, "\\");
		strcat_s(dirBuf, bufSize, configSuffix);
		return(TRUE);
	}
	else {
		return(FALSE);
	}
}

BOOL GetMyActionDeskDir(char dirBuf[], DWORD bufSize, int userId)
{
	char actionDir[256];
	if (GetActionDeskDir(actionDir, sizeof(actionDir))) {
		sprintf_s(dirBuf, bufSize, "%s\\%d", actionDir, userId);
		return(TRUE);
	}
	else {
		return(FALSE);
	}
}

BOOL GetPrioDirPath(char dirPathBuf[], DWORD bufSize, StringList* pOptDirList)
{
	for (DWORD i = 0; i < pOptDirList->Count(); i++) {
		const char* iterDir = pOptDirList->At(i);
		if (_access(iterDir, 0) == 0) {
			strcpy_s(dirPathBuf, bufSize, iterDir);
			return(TRUE);
		}
	}
	return(FALSE);
}

BOOL GetPrioFilePath(char filePathBuf[], DWORD bufSize, StringList* pOptDirList, const char* filename)
{
	char iterFilePath[256];
	for (DWORD i = 0; i < pOptDirList->Count(); i++) {
		const char* iterDir = pOptDirList->At(i);
		if (!strcmp(iterDir, "")) {
			strcpy_s(iterFilePath, sizeof(iterFilePath), filename);
		}
		else {
			strcpy_s(iterFilePath, sizeof(iterFilePath), iterDir);
			strcat_s(iterFilePath, sizeof(iterFilePath), "\\");
			strcat_s(iterFilePath, sizeof(iterFilePath), filename);
		}
		if (_access(iterFilePath, 0) == 0) {
			strcpy_s(filePathBuf, bufSize, iterFilePath);
			return(TRUE);
		}
	}
	return(FALSE);
}
